package mysql;

import yym.utils.Init;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;

public abstract class BaseDao {
    public Connection connection;
    public PreparedStatement pStmt;
    public ResultSet resultSet;

    //获取连接
    public boolean getConnection(){
        String url = Init.getInstance().getProperty("jdbc.connection.url");
        try {
            Class.forName(Init.getInstance().getProperty("jdbc.driver"));
            connection = DriverManager.getConnection(url,"root","yym980505");
            return true;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public Connection getConn(){
        try {
            Context cxt = new InitialContext();
            DataSource ds = (DataSource)cxt.lookup("java:comp/env/jdbc/news");
            connection = ds.getConnection();
            return connection;
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println("未连接");
        return null;
    }
    //销毁
    public void destroy(){
        try {
            if (resultSet!=null){
                resultSet.close();
            }
            if (pStmt!=null){
                pStmt.close();
            }
            if (connection!=null){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //增删改
    public int executeUpdate(String sql,Object[] params){
        int n = 0;
        if (getConnection()){
            try {
                pStmt = connection.prepareStatement(sql);
                for (int i = 0; i < params.length; i++) {
                    pStmt.setObject(i+1,params[i]);
                }
                n = pStmt.executeUpdate();
                System.out.println(n);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return n;
    }

    //查询
    public ResultSet executeQuery(String sql,Object[] params){
        if (this.getConnection()){
            try {
                pStmt = connection.prepareStatement(sql);
                for (int i = 0; i < params.length; i++) {
                    pStmt.setObject(i+1,params[i]);
                }
                resultSet = pStmt.executeQuery();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return resultSet;
    }
}
